
var ws;
var gloab_callback

// websocket初始化
const init = function (url, callback) {
    ws = new WebSocket(url);
    // 当连接上ws的时候触发
    ws.addEventListener("open", onOpen);
    // 当接收到消息的时候触发
    ws.addEventListener("message", onMessage);
    // 当连接关闭的时候触发
    ws.addEventListener("close", onClose);

    gloab_callback = callback; // 方法回调
}

const onOpen = (event) => {
    console.log("ws连接成功");
}

const onMessage = (event) => {
    console.log("vue接收到的后台数据", event.data);
    gloab_callback(event.data)
}

const onError = (event) => { }

const onClose = (event) => {
    console.log("ws连接断开");
}

// 客户端发送数据
const send = (msg) => {
    console.log("客户端发送消息");
    ws.send(msg)
}

// 关闭ws连接
const close = function (event) {
    // 断开websocket
    ws.close();
}


export default {
    init,
    send,
    close
}